// import '@/utils/css/ol.css';
import 'ol/ol.css'
import {
  Map,
  View
} from 'ol'
import TileLayer from 'ol/layer/Tile'
import ImageLayer from 'ol/layer/Image'
import Static from 'ol/source/ImageStatic'
import Projection from 'ol/proj/Projection'
import OSM from 'ol/source/OSM'
import {
  defaults as defaultControls
} from 'ol/control'
import {
  closestOnCircle,
  createStringXY
} from 'ol/coordinate'
import MousePosition from 'ol/control/MousePosition'
import {
  getCenter
} from 'ol/extent'
import {
  Draw,
  Modify,
  Snap,
  Select,
  Translate,
  Interaction,
  defaults as defaultInteractions,
  DragRotateAndZoom
} from 'ol/interaction.js'
import Overlay from 'ol/Overlay'
import {
  Vector as VectorLayer,
  Image
} from 'ol/layer.js'
import {
  Vector
} from 'ol/source.js'
import {
  GeoJSON
} from 'ol/format.js'

import {
  baseUrl
} from '@/utils/global'
import Cookie from 'js-cookie'

import {
  getLayerFenceDataList,
  getSingeFence,
  loadType,
  getAllFence
} from '@/api/system/historyDisplayInfo.js'
// import { map } from 'core-js/core/array';

import { unByKey } from 'ol/Observable'
import { getVectorContext } from 'ol/render'
import { easeIn, easeOut } from 'ol/easing'
import {
  Circle,
  Fill,
  Stroke,
  Style,
  Text,
  Icon,
  Circle as CircleStyle
} from 'ol/style.js'

let _this = null // 用来存储Vue实例this
let _iMap = null
let _iMap2 = null
var _tileLayer = null
let _dPR
let _dPR2
let _zero
let _Style
let OverlayPopup
let measureTooltipElement
let measureTooltip
let tagTypes
var mapZoom = 2
var FenceSource = null
var FenceLayer = null
let cameraSource
let cameraLayer

var FenceSource2
var FenceLayer2

// 传递this对象
function sendThis(vm) {
  _this = vm
}

function Load_Map(url, RealWidth, RealHeight, PixelWidth, PixelHeight, dPR, ZeroPoint, param) {
  _dPR = dPR
  _zero = _TransPixel(ZeroPoint)
  var left = _zero[0]
  var bottom = _zero[1] + (-PixelHeight)
  var right = _zero[0] + PixelWidth
  var top = _zero[1]
  var _Projection = new Projection({
    code: 'EPSG:3857',
    units: 'pixels',
    extent: [left, bottom, right, top]
  })

  // _tileLayer = new TileLayer({
  //   source: new OSM({
  //     wrapX: false
  //   })
  // })
  _iMap = new Map({
    interactions: defaultInteractions().extend([
      new DragRotateAndZoom()
    ]),
    target: 'map',
    layers: [
      new ImageLayer({
        source: new Static({
          url: url,
          projection: _Projection,
          imageExtent: [left, bottom, right, top]
        })
      })

    ],
    view: new View({
      projection: _Projection,
      center: getCenter([left, bottom, right, top]),
      zoom: 2,
      maxZoom: 8
    })
  })

  _iMap.on('pointermove', MapPointerMove) // 监听鼠标移动事件
  _iMap.getView().on('change:resolution', calcScale) // 监听地图缩放事件
  calcScale()
  if (param) {
    _iMap.on('click', MapClick) // 监听点击事件
    var element = document.getElementById('popup').cloneNode(true)
    element.style.display = 'block'
    var Popup = new Overlay({
      id: 'popup_',
      autoPan: true, // 点击地图边缘时，地图自动调节
      element: element,
      positioning: 'center-center',
      position: undefined
    })
    _iMap.addOverlay(Popup)
  }
}

function Load_TrackMap(url, RealWidth, RealHeight, PixelWidth, PixelHeight, dPR, ZeroPoint) {
  _dPR2 = dPR
  const _zero = _TransPixel(ZeroPoint)
  var left = _zero[0]
  var bottom = _zero[1] + (-PixelHeight)
  var right = _zero[0] + PixelWidth
  var top = _zero[1]
  var _Projection = new Projection({
    code: 'EPSG:3857',
    units: 'pixels',
    extent: [left, bottom, right, top]
  })

  _iMap2 = new Map({
    interactions: defaultInteractions().extend([
      new DragRotateAndZoom()
    ]),
    target: 'map2',
    layers: [
      new ImageLayer({
        source: new Static({
          url: url,
          projection: _Projection,
          imageExtent: [left, bottom, right, top]
        })
      })
    ],
    view: new View({
      projection: _Projection,
      center: getCenter([left, bottom, right, top]),
      zoom: 2,
      maxZoom: 8
    })
  })
}

// 坐标函数
function MapPointerMove(evt) {
  if (evt.dragging) {
    return
  }
  var pixel = _iMap.getEventPixel(evt.originalEvent)
  var hit = _iMap.hasFeatureAtPixel(pixel)
  _iMap.getTargetElement().style.zIndex = 1
  if (hit) {
    _iMap.getTargetElement().style.cursor = 'pointer'
  } else {
    _iMap.getTargetElement().style.cursor = ''
  }
  var coord = _TransMetric_XY(evt.coordinate, 2)
  $('.positiondiv span').html(coord)
}

// 输出坐标点位置
function _TransMetric_XY(c, fix) {
  var X = (c[0] / _dPR).toFixed(fix)
  var Y = (c[1] / _dPR).toFixed(fix) * -1
  var M = [X, Y]
  var M = 'X:' + X + '  ' + 'Y:' + Y
  return M
}
// 坐标（锚点、标签） 转换成像素(米-》像素)
function _TransPixel(c) {
  var PX
  $.each(c, function(i, item) {
    if (item == undefined || item.length == undefined) {
      var X = c[0] * _dPR
      var Y = _validate(c[1]) * _dPR
      PX = [X, Y]
    } else {
      $.each(c, function(i, item) {
        var j, jj
        for (j = 0, jj = item.length; j < jj; ++j) {
          item[j] = [item[j][0] * _dPR, _validate(item[j][1]) * _dPR]
        }
        PX = [item]
      })
    }
  })
  return PX
}

// 坐标（锚点、标签）  转换成米（像素-》米）
function _TransMetric(c) {
  var M = []
  c.forEach(function(item) {
    if (item.length == undefined) {
      var X = (c[0] / _dPR).toFixed(2)
      var Y = _validate((c[1] / _dPR)).toFixed(2)
      M = [X, Y]
    } else {
      M.push('[' + [(item[0] / _dPR).toFixed(2), (_validate(item[1]) / _dPR).toFixed(2)] + ']')
    }
  })
  return M
}

function _TransMetric2(c, fix) {
  var M
  $.each(c, function(i, item) {
    if (item.length == undefined) {
      var X = (c[0] / _dPR).toFixed(fix)
      var Y = _validate((c[1] / _dPR)).toFixed(fix)
      M = [X, Y]
    } else {
      $.each(c, function(i, item) {
        var j, jj
        for (j = 0, jj = item.length; j < jj; ++j) {
          item[j] = '[' + [(item[j][0] / _dPR).toFixed(fix), (_validate(item[j][1]) / _dPR).toFixed(fix)] + ']'
        }
        M = [item]
      })
    }
  })
  return M
}

function _TransMetric3(c, fix) {
  var M
  $.each(c, function(i, item) {
    if (item.length == undefined) {
      var X = (c[0] / _dPR).toFixed(fix)
      var Y = _validate((c[1] / _dPR)).toFixed(fix)
      M = [X, Y]
    } else {
      $.each(c, function(i, item) {
        var j, jj
        for (j = 0, jj = item.length; j < jj; ++j) {
          item[j] = [(item[j][0] / _dPR).toFixed(fix), (_validate(item[j][1]) / _dPR).toFixed(fix)]
        }
        M = item
      })
    }
  })
  return M
}

function createMeasureTooltip() {
  if (measureTooltipElement) {
    measureTooltipElement.parentNode.removeChild(measureTooltipElement)
  }
  measureTooltipElement = document.createElement('div')
  measureTooltipElement.className = 'ol-tooltip ol-tooltip-measure'
  measureTooltip = new Overlay({
    element: measureTooltipElement,
    offset: [0, -15],
    positioning: 'bottom-center'
  })
  _iMap.addOverlay(measureTooltip)
}
// 坐标（电子围栏页面显示标尺）像素-》米
function _TransMetricFence(c) {
  var M = []
  c.forEach(function(item) {
    if (item.length == undefined) {
      var X = (c[0] / _dPR).toFixed(2)
      var Y = (c[1] / _dPR)
      M = [X, Y]
    } else {
      M.push([(item[0] / _dPR).toFixed(2), (-(item[1] / _dPR)).toFixed(2)])
    }
  })
  return '长:' + (parseFloat(M[1][0]) - parseFloat(M[0][0])).toFixed(2) + '宽' + (parseFloat(M[1][1]) - parseFloat(M[2][1])).toFixed(2)
}
// 监听地图缩放事件
function calcScale() {
  mapZoom = _iMap.getView().getZoom()
  const res = _iMap.getView().getResolution()
  const temp = (100 / _dPR) * res
  $('.scalediv span').html(temp.toFixed(2) + 'M')
}
// 取数字的绝对值
function _validate(num) {
  var reg = /^\d+(?=\.{0,1}\d+$|$)/
  if (reg.test(num)) return -(num)
  return Math.abs(num)
}
// 获取目前所有数据类型
function LoadTypeData() {
  tagTypes = []
  loadType().then(data => {
    if (data.code === 200) {
      // 按大类进行分类整理
      const datas = data.data
      for (let i = 0; i < datas.length; i++) {
        const type = datas[i].type
        if (tagTypes[type]) {
          tagTypes[type].push(datas[i])
        } else {
          tagTypes[type] = []
          tagTypes[type].push(datas[i])
        }
      }
    }
  })
}
LoadTypeData()

// 标签样式设置
function TagStyle(f, rontation) {
  let textname = ''
  let iconsrc = ''
  let iconcolor = ''
  // const statusAlarm = (f.get('isForLife')).toString ? '--' + f.get('isForLife') : ''
  textname = mapZoom >= 2 ? f.get('name') + f.get('tag_id') : ''

  // 判断标签的类型及工种，用来显示不同的图标和颜色
  if (tagTypes[f.get('type')]) {
    const subtypes = tagTypes[f.get('type')]

    var b = -1
    for (let i = 0; i < subtypes.length; i++) {
      if (subtypes[i].name === f.get('workTypeName')) {
        b = i
        break
      }
    }
    if (b != -1) { // 有这种类型的工种
      iconsrc = '/static/icon/' + subtypes[b].icon + '.png'
      iconcolor = subtypes[b].color
    } else {
      iconsrc = '/static/icon/5ren.png'
      iconcolor = '#409EFF'
    }
  } else {
    // 如果没有这种大类，使用默认图标
    iconsrc = '/static/icon/5ren.png'
    iconcolor = '#409EFF'
  }
  if (!f.get('visible')) {
    return null
  }
  return [
    _Style = new Style({
      image: new Icon({
        src: iconsrc,
        color: iconcolor
      }),
      text: new Text({
        text: textname,
        offsetY: 14,
        fill: new Fill({
          color: '#fff'
        }),
        stroke: new Stroke({
          color: '#000',
          width: 3
        }),
        rotation: rontation
      })
    })
  ]
}

function MapClick(evt) {
  _this.isPopup = true
  _this.isNoPopup = true
  var feature
  if (evt.pixel != undefined) {
    // 针对矢量数据源，通过鼠标点击坐标与map坐标对比，获取选中要素，openlayers提供了相关函数
    feature = _iMap.forEachFeatureAtPixel(evt.pixel, function(feature, layer) {
      var type = feature.getGeometry().getType()
      var property = feature.getProperties()
      // var coordinate = ——.extent.getCenter(feature.getGeometry().getExtent())

      return feature
    })
  } else {
    feature = evt
  }

  _this.noTagIcon = feature
  if (feature) {
    // console.log('XXX', _this.isNoPopup && _this.noTagIcon)
    const type = feature.get('type')
    if (type === 'staff' || type === 'car' || type === 'material' || type === 'signange' || type === 'workingHoursOrder' || type === 'bucket') {
      _Popup(feature, feature.getGeometry().getCoordinates())
    }
  }
}
function MapClickShrink(evt) {
  // console.log('', evt.getGeometry().getCoordinates(), _TransPixel(evt.getGeometry().getCoordinates()), evt)
  _this.isPopup = true
  _this.isNoPopup = true
  _this.noTagIcon = evt
  if (evt) {
    _Popup(evt, evt.getGeometry().getCoordinates())
  }
}

function _Popup(f, pos) {
  OverlayPopup = _iMap.getOverlayById('popup_')
  const content = $(OverlayPopup.getElement()).find('#popup-content')
  const closer = $(OverlayPopup.getElement()).find('#popup-closer')
  const trackHistory = $(OverlayPopup.getElement()).find('#trackHistory')

  trackHistory.on('click', function() {
    _this.isDialog = true
  })
  closer.click(function() {
    _this.isPopup = false
    _this.isNoPopup = false
    _this.noTagIcon = null
    _this.isNoTagIcon = false
    OverlayPopup.setPosition(undefined)
    this.blur()
    return false
  })
  OverlayPopup.setPosition(pos)
  OverlayPopup.set('idx_', f.getId())
  _this.featureId = f.getId()

  if (f) {
    var c
    const fAlarm = f.get('isForLife') == 0 ? '正常' : f.get('isForLife') == 1 ? '超时告警' : f.get('isForLife') == 2 ? '跳检告警' : '未定义'
    switch (f.get('type')) {
      case 'staff':
        c = `
        <div>车辆信息</div>
        <div>编号：${f.get('tag_id')}</div>
        <div>名称${f.get('itemname')}</div>
        <div>坐标：${_TransMetric(pos)}</div>
        <div>类型：${f.get('type')}</div>
        <div>vin码${f.get('resourceId')}</div>
        <div>后四位vin码${f.get('name')}</div>
        <div>告警状态：${fAlarm}</div>
        `
        // c = '<li>编号：' + f.get('resourceId') + '</li><li>名称：' + f.get('itemname') + '</li><li>坐标：' + _TransMetric(pos) + '</li><li>数量：' + +'</li><li>状态：' + +'</li>'
        break

      default:
        _this.msgSuccess('该类型非staff')
        _this.isNoPopup = false
        _this.noTagIcon = null
        OverlayPopup.setPosition(undefined)
        break
    }
    content.html(c)
  } else {
    OverlayPopup.setPosition(undefined)
  }
}

// 更新overlay位置
function updateOverPopupPosition(f, ncoords) {
  const OverlayPopup = _iMap.getOverlayById('popup_')
  if (OverlayPopup.getPosition()) {
    if (f.getId() == OverlayPopup.get('idx_')) {
      const content = $(OverlayPopup.getElement()).find('#popup-content')
      if (f) {
        var c
        const fAlarm = f.get('isForLife') == 0 ? '正常' : f.get('isForLife') == 1 ? '超时告警' : f.get('isForLife') == 2 ? '跳检告警' : '未定义'
        switch (f.get('type')) {
          case 'staff':
            c = `
            <h4>车辆信息</h4>
            <div>编号：${f.get('resourceId')}</div>
            <div>坐标：${_TransMetric(ncoords)}</div>
            <div>数量：${f.get('resourceId')}</div>
            <div>vin码${f.get('resourceId')}</div>
            <div>告警状态：${fAlarm}</div>
            `
            // c = '<li>编号：' + f.get('resourceId') + '</li><li>名称：' + f.get('itemname') + '</li><li>坐标：' + _TransMetric(ncoords) + '</li><li>数量：' + +'</li><li>状态：' + +'</li>'
            break
          default:
            break
        }
        content.html(c)
      } else {
        OverlayPopup.setPosition(undefined)
      }
      OverlayPopup.setPosition(ncoords)
    }
  }
}

function FenceStyle(f, r) {
  const name = f.get('name')
  // let name = f.get('remark');
  // if (name == undefined || name == null || name == "" || name == "无") {
  //   name = f.get('name')
  // }
  return [
    new Style({
      fill: new Fill({
        color: 'rgba(' + r + ',0.1)'
      }),
      stroke: new Stroke({
        lineDash: [1, 2, 3, 4, 5, 6],
        color: 'rgb(' + r + ')',
        width: 2
      }),
      image: new Circle({
        radius: 7,
        fill: new Fill({
          color: '#FF0000'
        })
      }),
      text: new Text({
        text: name,
        font: 'bold 14px Arial',
        textAlign: 'center',
        textBaseline: 'middle',
        overflow: true,
        offsetX: 0,
        offsetY: 0,
        fill: new Fill({
          color: '#FF0000'
        }),
        stroke: new Stroke({
          color: '#fff',
          width: 3
        })
      })
    })
  ]
}

// 增加电子围栏
function Load_Fence(Geo) {
  if (FenceLayer != null) {
    _iMap.removeLayer(FenceLayer)
    FenceSource = null
    FenceLayer = null
  }
  FenceSource = new Vector({
    wrapX: false
  })
  FenceLayer = new VectorLayer({
    minResolution: 0,
    maxResolution: _dPR * 1.2,
    source: FenceSource,
    style: function(feature, resolution) {
      const fenceType = feature.get('fencetype')
      if (feature.get('id') == undefined) {
        return FenceStyle(feature, '255, 0, 0')
      }
      if (!(typeof fenceType === 'undefined')) {
        const arr = fenceType.split(',')
        if (arr.length > 1) {
          return FenceStyle(feature, '165,42,42')
        }
      }

      if (fenceType == 'camera') {
        return FenceStyle(feature, '0, 153, 102')
      } else if (fenceType == 'operation') {
        return FenceStyle(feature, '0,153,204')
      } else if (fenceType == 'alarm') {
        return FenceStyle(feature, '255,0,0')
      } else if (fenceType == 'check') {
        return FenceStyle(feature, '255,255,0')
      } else if (fenceType == 'polling') {
        return FenceStyle(feature, '255,165,0')
      } else {
        return FenceStyle(feature, '160,32,240')
      }
    }
  })
  _iMap.addLayer(FenceLayer)
  if (Geo != '') {
    FenceAjax(Geo, FenceSource)
  }
}
// 增加电子围栏
function Load_Fence2() {
  if (FenceLayer2 != null) {
    FenceSource2.clear()
    _iMap.removeLayer(FenceLayer2)
    FenceSource2 = null
    FenceLayer2 = null
  }
  FenceSource2 = new Vector({
    wrapX: false
  })
  FenceLayer2 = new VectorLayer({
    minResolution: 0,
    maxResolution: _dPR * 1.2,
    source: FenceSource2,
    style: function(feature, resolution) {
      const fenceType = feature.get('fencetype')
      if (feature.get('id') == undefined) {
        return FenceStyle(feature, '255, 0, 0')
      }
      if (!(typeof fenceType === 'undefined')) {
        const arr = fenceType.split(',')
        if (arr.length > 1) {
          return FenceStyle(feature, '165,42,42')
        }
      }

      if (fenceType == 'camera') {
        return FenceStyle(feature, '0, 153, 102')
      } else if (fenceType == 'operation') {
        return FenceStyle(feature, '0,153,204')
      } else if (fenceType == 'alarm') {
        return FenceStyle(feature, '255,0,0')
      } else if (fenceType == 'check') {
        return FenceStyle(feature, '255,255,0')
      } else if (fenceType == 'polling') {
        return FenceStyle(feature, '255,165,0')
      } else {
        return FenceStyle(feature, '160,32,240')
      }
    }
  })
  _iMap.addLayer(FenceLayer2)
}
/**
 * AJAX获取电子围栏GeoJson数据
 */
function FenceAjax(Geo, source) {
  getAllFence(Geo).then(res => {
    var format = new GeoJSON()
    if (res.code == 200) {
      if (res.data.length > 0) {
        for (let i = 0; i < res.data.length; i++) {
          var newFeatures = format.readFeatures(res.data[i])
          newFeatures.forEach(function(f) {
            if (f.get('fencetype') != 'layer' && f.get('fencetype') != 'temporary') {
              var coord = f.getGeometry().getCoordinates()
              f.getGeometry().setCoordinates(_TransPixel(coord))
              f.setId(f.get('id'))
              source.addFeature(f)
            }
          })
        }
      }
    }
  })
}
// 释放围栏容器
function releaseFence() {
  if (FenceSource != null) {
    const old = FenceSource.getFeatures()
    let len = old.length
    while (len > 0) {
      len--
      FenceSource.removeFeature(old[len])
      old.splice(len, 1)
    }
  }
  if (FenceLayer != null) {
    _iMap.removeLayer(FenceLayer)
  }

  FenceSource = null
  FenceLayer = null
}

// 获取围栏资源列表
function getFenceList(mapId) {
  getLayerFenceDataList(mapId).then(res => {
    if (res.code == 200) {
      _this.tableFence = res.data
      _this.tableFence.forEach((val) => {
        val.layerName = null
        val.creator = null
      })
    }
  })
}

function flashDot(feature, _tileLayer) {
  const start = Date.now()
  const flashGeom = feature.getGeometry().clone()
  // const flashGeom = _TransPixel(feature.getGeometry().getCoordinates()).clone()
  const listenerKey = _tileLayer.on('postrender', animate)
  // const listenerKey = this.tileLayer.on("postcompose", animate);
  // const self = this
  const duration = 1000
  function animate(event) {
    const frameState = event.frameState
    const elapsed = frameState.time - start
    if (elapsed >= duration) {
      unByKey(listenerKey)
      return
    }
    const vectorContext = getVectorContext(event)
    const elapsedRatio = elapsed / duration
    // radius will be 5 at start and 30 at end.
    const radius = easeOut(elapsedRatio) * 20 + 2
    const opacity = easeOut(1 - elapsedRatio)

    const style = new Style({
      image: new CircleStyle({
        radius: radius,
        stroke: new Stroke({
          color: 'rgba(255, 0, 0, ' + opacity + ')',
          // width: 0.25 + opacity,
          width: 2 + opacity
        })
      })
    })

    vectorContext.setStyle(style)
    vectorContext.drawGeometry(flashGeom)
    // tell OpenLayers to continue postrender animation
    _iMap.render()
  }
}

// 通过围栏id加载单个围栏或多个
function addSingleFence(param) {
  if (FenceLayer != null) {
    _iMap.removeLayer(FenceLayer)
    FenceSource = null
    FenceLayer = null
  }
  FenceSource = new Vector({
    wrapX: false
  })
  FenceLayer = new VectorLayer({
    minResolution: 0,
    maxResolution: _dPR * 1.2,
    source: FenceSource,
    style: function(feature, resolution) {
      const fenceType = feature.get('fencetype')
      if (feature.get('id') == undefined) {
        return FenceStyle(feature, '255, 0, 0')
      }
      if (!(typeof fenceType === 'undefined')) {
        const arr = fenceType.split(',')
        if (arr.length > 1) {
          return FenceStyle(feature, '165,42,42')
        }
      }

      if (fenceType == 'camera') {
        return FenceStyle(feature, '0, 153, 102')
      } else if (fenceType == 'operation') {
        return FenceStyle(feature, '0,153,204')
      } else if (fenceType == 'alarm') {
        return FenceStyle(feature, '255,0,0')
      } else if (fenceType == 'check') {
        return FenceStyle(feature, '255,255,0')
      } else if (fenceType == 'polling') {
        return FenceStyle(feature, '255,165,0')
      } else {
        return FenceStyle(feature, '160,32,240')
      }
    }
  })
  _iMap.addLayer(FenceLayer)
  if (typeof param === 'number') {
    getSingeFence(param).then(res => {
      var format = new GeoJSON()
      var newFeatures = format.readFeatures(res.data[0])
      newFeatures.forEach(function(f) {
        if (f.get('fencetype') != 'layer' && f.get('fencetype') != 'temporary') {
          var coord = f.getGeometry().getCoordinates()
          f.getGeometry().setCoordinates(_TransPixel(coord))
          f.setId(f.get('id'))
          FenceSource.addFeature(f)
        }
      })
    })
  } else {
    param.forEach((val) => {
      getSingeFence(val.idx).then(res => {
        var format = new GeoJSON()
        var newFeatures = format.readFeatures(res.data[0])
        newFeatures.forEach(function(f) {
          if (f.get('fencetype') != 'layer' && f.get('fencetype') != 'temporary') {
            var coord = f.getGeometry().getCoordinates()
            f.getGeometry().setCoordinates(_TransPixel(coord))
            f.setId(f.get('id'))
            FenceSource.addFeature(f)
          }
        })
      })
    })
  }
}
// 根据围栏id修改单个电子围栏的样式信息
function getFenceById(fenceId, color1, color2, fenceType, fenceName) {
  if (FenceSource == null) {
    _this.$message({
      message: '围栏未被勾选显示'
    })
  }

  if (color1 == null) {
    if (fenceType == 'camera') {
      color1 = 'rgba(0, 153, 102,0.1)'
    } else if (fenceType == 'operation') {
      color1 = 'rgba(0,153,204,0.1)'
    } else if (fenceType == 'alarm') {
      color1 = 'rgba(255,0,0,0.1)'
    } else if (fenceType == 'check') {
      color1 = 'rgba(255,255,0,0.1)'
    } else if (fenceType == 'polling') {
      color1 = 'rgba(255,165,0,0.1)'
    } else {
      color1 = 'rgba(160,32,240,0.1)'
    }
  }

  if (color2 == null) {
    if (fenceType == 'camera') {
      color2 = 'rgba(0, 153, 102,1)'
    } else if (fenceType == 'operation') {
      color2 = 'rgba(0,153,204,1)'
    } else if (fenceType == 'alarm') {
      color2 = 'rgba(255,0,0,1)'
    } else if (fenceType == 'check') {
      color2 = 'rgba(255,255,0,1)'
    } else if (fenceType == 'polling') {
      color2 = 'rgba(255,165,0,1)'
    } else {
      color2 = 'rgba(160,32,240,1)'
    }
  }

  var feature = FenceSource.getFeatureById(fenceId)
  feature.setStyle(new Style({
    fill: new Fill({
      color: color1
    }),
    stroke: new Stroke({
      lineDash: [1, 2, 3, 4, 5, 6],
      color: color2,
      width: 2
    }),
    image: new Circle({
      radius: 7,
      fill: new Fill({
        color: '#FF0000'
      })
    }),
    text: new Text({
      text: fenceName,
      font: 'bold 14px Arial',
      textAlign: 'center',
      textBaseline: 'middle',
      offsetX: 0,
      offsetY: 0,
      fill: new Fill({
        color: '#FF0000'
      }),
      stroke: new Stroke({
        color: '#fff',
        width: 3
      })
    })
  }))
}
export {
  _Popup,
  sendThis,
  Load_Map,
  _TransPixel,
  TagStyle,
  updateOverPopupPosition,
  FenceStyle,
  _TransMetric,
  _TransMetric2,
  _TransMetric3,
  _TransMetricFence,
  createMeasureTooltip,
  Load_Fence,
  Load_Fence2,
  releaseFence,
  getFenceList,
  addSingleFence,
  getFenceById,
  Load_TrackMap,
  MapClick,
  MapClickShrink,
  flashDot,
  FenceSource,
  FenceSource2,
  _iMap,
  _iMap2,
  _Style,
  _dPR,
  tagTypes
}
